<?php
class UsersController extends AppController {
    public $name    = 'Users';
    public $helpers = array('Form');

    public function login () {
        $form = $this->params['form'];

        $data = $this->User->find('first', array(
            'conditions' => array(
                'User.username' => $form['username'],
                'User.password' => $form['password']
            ),
            'recursive'  => -1,
            'fields'     => array('User.id', 'User.fullname', 'User.position', 'User.level', 'User.status')
        ));

        if (!$data) {
            $json = array(
                'status' => false,
                'mesg'   => __('Invalid username or password', true)
            );

            $this->response($json);
            return;
        } else if ($data['User']['status'] != 'A') {
            $json = array(
                'status' => false,
                'mesg'   => __('Account inactive, please contact administrator', true)
            );

            $this->response($json);
            return;
        }

        $this->User->id = $data['User']['id'];
        $this->User->saveField('last_login', date('Y-m-d H:i:s'));
        $this->Session->write('User', $data['User']);

        $json = array(
            'status' => true,
            'userid' => $data['User']['id'],
            'mesg'   => __('Welcome back', true)
        );

        $this->response($json);
    } // login

    public function logout () {
        $bool = $this->Session->del('User');

        $json = array(
            'status' => true
        );

        $this->response($json);
    } // logout
} // UsersController
?>